<template>
  <div class="app-container">

    <!--<el-row :gutter="10" class="mb8">-->
      <!--<el-col :span="1.5">-->
        <!--<el-button-->
          <!--type="info"-->
          <!--plain-->
          <!--icon="el-icon-upload2"-->
          <!--:disabled="!orderInfo.no"-->
          <!--size="mini"-->
          <!--@click="handleImport"-->
          <!--v-hasPermi="['quality:qualityTaskDetail:importData']"-->
        <!--&gt;导入质检结果</el-button>-->
      <!--</el-col>-->

    <!--</el-row>-->

    <el-table height="25vh" v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <af-table-column label="条码" align="center" prop="barcode" />
      <af-table-column label="质检项名称" align="center" prop="itemName" />
      <el-table-column label="值类型" align="center" prop="valueType" >
        <template slot-scope="scope">
          <dict-tag :options="valueTypeList" :value="scope.row.valueType"/>
        </template>
      </el-table-column>
      <af-table-column label="实际值" align="center" prop="actualValue" />
      <el-table-column label="检验结果" align="center" prop="qualityResult" />
    </el-table>


    <!-- 添加或修改单据明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="质检项" prop="itemNo">
          <el-select @change="changeQualityItem" style="width:100%;" v-model="form.itemNo" filterable placeholder="请选择质检项">
            <el-option
              v-for="dict in qualityItemList"
              :key="dict.no"
              :label="dict.name"
              :value="dict.no"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="值类型" prop="valueType">
          <el-select disabled v-model="form.valueType" style="width:100%;" placeholder="值类型" >
            <el-option
              v-for="item in valueTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标准下限" v-if="form.valueType == 'RANGE'"  prop="lowerLimitValue">
          <el-input v-model.trim="form.lowerLimitValue" placeholder="请输入标准下限" />
        </el-form-item>

        <el-form-item label="标准上限" v-if="form.valueType == 'RANGE'" prop="upperLimitValue">
          <el-input v-model.trim="form.upperLimitValue" placeholder="请输入标准上限" />
        </el-form-item>

        <el-form-item label="方法" prop="method">
          <el-input v-model.trim="form.method" placeholder="请输入方法" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?taskNo=' + orderInfo.no"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listQualityItem,listTaskDetail, getQualityItemDetail, delQualityItemDetail, addQualityItemDetail, updateQualityItemDetail } from "./api/quelityItemDetail";
import { isEmpty, isQualityFour} from '@/utils/validate';
import { getToken } from "@/utils/auth";
export default {
  name: "salesOrderDetail",
  dicts: ['basic_product_type'],
  props:{
    orderData:{}
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 已选择的质检项
      notInNos: [],
      productNos: [],
      pitchOnTotalOrderQty: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据明细表格数据
      detailList: [],
      // 质检项列表
      qualityItemList: [],
      valueTypeList:[
        {
          id:0,
          label:'范围值',
          value:'RANGE'
        },
        {
          id:1,
          label:'状态值',
          value:'STATUS'
        },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/quality/qualityTaskDetail/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 99999,
        no: null,
        batchNo: null,
        productNo: null,
        storehouseLocationNo: null,
        picker: null,
        orderDetailStatus: null,
        createUser: null,
        updateUser: null,
        sort: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemNo: [
          { required: true, message: "质检项不能为空", trigger: "change" }
        ],
        upperLimitValue: [
          { required: true, message: "标准上限不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if ((isEmpty(value) || isQualityFour(value))) {
                callback();
              } else {
                callback('请输入数值，保留4位小数');
              }
            },
            trigger: "blur",
          },
        ],
        lowerLimitValue: [
          { required: true, message: "标准下限不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if ((isEmpty(value) || isQualityFour(value))) {
                callback();
              } else {
                callback('请输入数值，保留4位小数');
              }
            },
            trigger: "blur",
          },
        ],
      },
      // 订单信息
      orderInfo:{
        no : null
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 监视订单信息变动
    orderData(newValue){
      if(!newValue || !newValue.no){
        this.orderInfo = {no : null};
      }else {
        this.orderInfo = newValue;
      }
      this.getList();
    }
  },
  methods: {
    /** 获取质检项列表 */
    getListQuality(){
      listQualityItem({
        pageNum:1,
        pageSize:0,
        notInNos:this.notInNos
      }).then(response => {
        this.qualityItemList = response.rows;
      });
    },
    // 修改物料
    changeQualityItem(){
      const qualityItem = this.qualityItemList.find(item => item.no === this.form.itemNo)
      this.$set(this.form,'itemName',qualityItem.name);
      this.$set(this.form,'valueType',qualityItem.valueType);
      this.$set(this.form,'upperLimitValue',qualityItem.upperLimitValue);
      this.$set(this.form,'lowerLimitValue',qualityItem.lowerLimitValue);
      this.$set(this.form,'method',qualityItem.method);
    },
    /** 查询单据明细列表 */
    getList() {
      this.loading = true;
      this.queryParams.taskNo = this.orderInfo.no;
      if(!this.queryParams.taskNo){
        this.detailList = [];
        this.total = 0;
        this.loading = false;
        return;
      }
      listTaskDetail(this.queryParams).then(response => {
        this.detailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$set(this,'queryParams',{});
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.itemNos = selection.map(item => item.itemNo)
      this.pitchOnTotalOrderQty = 0;
      selection.forEach(item => this.pitchOnTotalOrderQty = this.pitchOnTotalOrderQty + item.orderQty);
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.productNo = this.orderInfo.productNo;
      this.open = true;
      // 过滤已存在的质检项
      this.detailList.forEach((row) => {
        this.notInNos.push(row.itemNo);
      });
      // 重新获取物料列表
      this.getListQuality();
      this.title = "添加质检项";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // 过滤BOM主表的物料以及明细已有的物料
      this.$set(this,'notInNos',[]);
      this.detailList.forEach((row) => {
        if (row.itemNo != this.itemNos[0]) {
          this.notInNos.push(row.itemNo);
        }
      });

      // 重新获取物料列表
      this.getListQuality();
      const id = row.id || this.ids
      getQualityItemDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改BOM组件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lowerLimitValue && this.form.upperLimitValue) {
            if (this.form.lowerLimitValue > this.form.upperLimitValue) {
              this.$modal.msgWarning("标准上限不能小于标准下限");
              return;
            }
          }
          if (this.form.id != null) {
            updateQualityItemDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQualityItemDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
        return delQualityItemDetail(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "质检结果导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      const a = document.createElement('a');
      a.href = `${process.env.BASE_URL}static/file/质检任务明细导入模板.xlsx` //'./static/file/物料BOM导入模板.xlsx';
      a.click();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
